package org.learn.spring_quartz.controller;

import org.learn.spring_quartz.job.WebJob;
import org.learn.spring_quartz.lib.MyHolidayCalendar;
import org.quartz.*;
import lombok.extern.slf4j.Slf4j;
import org.learn.spring_quartz.bean.RestTemplateConfig;
import org.learn.spring_quartz.dto.RequestJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@RestController
@RequestMapping("/scheduler")
public class IndexController {
    @Autowired
    private Scheduler scheduler ;

    @PostMapping("/start")
    public String startJob(@RequestBody RequestJob job) throws SchedulerException {

//        MyHolidayCalendar.addCalendar();
        String cron = job.getCron();
        JobDetail jobDetail = JobBuilder.newJob(WebJob.class).withIdentity("httpJob", "group1").usingJobData("url", "http://localhost:80").build();
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("httpTrigger", "group1").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
        scheduler.scheduleJob(jobDetail, trigger);
        return "任务已启动, cron: " + job.getCron();
    }

    @PostMapping("/update")
    public String updateJob(@RequestBody RequestJob job) throws SchedulerException {
        String cron = job.getCron();
        TriggerKey triggerKey = TriggerKey.triggerKey("httpTrigger", "group1");
        Trigger newTrigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        scheduler.rescheduleJob(triggerKey, newTrigger);
        return "任务已更新，新的 cron: " + cron;
    }
    @PostMapping("/stop")
    public String stopJob() throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey("httpJob", "group1"));
        return "任务已暂停";
    }

    @PostMapping("/resume")
    public String resumeJob() throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey("httpJob", "group1"));
        return "任务已恢复";
    }

    @PostMapping("/delete")
    public String deleteJob(@RequestBody RequestJob job) throws SchedulerException {
        scheduler.deleteJob(JobKey.jobKey("httpJob", "group1"));
        return "任务已删除";
    }
}
